<?php

declare(strict_types=1);
/**
 * This file is part of MoChat.
 * @link     https://mo.chat
 * @document https://mochat.wiki
 * @contact  group@mo.chat
 * @license  https://github.com/mochat-cloud/mochat/blob/master/LICENSE
 */

namespace MoChat\App\Client\Action\Dashboard\Tag;

use Hyperf\Di\Annotation\Inject;
use Hyperf\HttpServer\Annotation\Controller;
use Hyperf\HttpServer\Annotation\Middleware;
use Hyperf\HttpServer\Annotation\Middlewares;
use Hyperf\HttpServer\Annotation\RequestMapping;
use MoChat\App\Client\Contract\ClientTagContract;
use MoChat\App\Client\Contract\ClientTagGroupContract;
use MoChat\App\Common\Middleware\DashboardAuthMiddleware;
use MoChat\App\WorkContact\Logic\Tag\StoreLogic;
use MoChat\App\WorkContact\QueueService\Tag\StoreApply;
use MoChat\Framework\Action\AbstractAction;
use MoChat\Framework\Constants\ErrorCode;
use MoChat\Framework\Exception\CommonException;
use MoChat\Framework\Request\ValidateSceneTrait;

/**
 * 创建客户标签.
 *
 * Class Store
 * @Controller
 */
class Store extends AbstractAction
{
    use ValidateSceneTrait;

    /**
     * @Inject
     * @var ClientTagGroupContract
     */
    protected $clientTagGroupService;

    /**
     * @Inject
     * @var ClientTagContract
     */
    protected $clientTagService;

    /**
     * @Middlewares({
     *     @Middleware(DashboardAuthMiddleware::class)
     * })
     * @RequestMapping(path="/dashboard/clientTag/store", methods="POST")
     */
    public function handle()
    {
        // 接收参数
        $params['groupId'] = $this->request->input('groupId');
        $params['tagName'] = $this->request->input('tagName');

        // 验证参数
        $this->validated($params);

        $this->service = make(StoreApply::class);

        $corpId = user()['corpIds'];
        if (count($corpId) != 1) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '请先选择企业');
        }
        $count = $this->clientTagService->countWorkContactTagByGroupId($params['groupId']);
        $data = []; // 本地存储
        foreach ($params['tagName'] as $val) {
            if (empty($val)) {
                throw new CommonException(ErrorCode::INVALID_PARAMS, '标签名不能为空');
            }
            ++$count;
            $data[] = [
                'corp_id' => user()['corpIds'][0],
                'client_tag_group_id' => $params['groupId'],
                'name' => $val,
                'order' => $count,
            ];
        }
        // 查询该分组下是否已存在相同标签名称
        $info = $this->clientTagService
            ->getWorkContactTagsByNamesGroupId($params['tagName'], $params['groupId']);

        if (!empty($info)) {
            throw new CommonException(ErrorCode::INVALID_PARAMS, '该分组下已存在相同标签名');
        }

        $res = $this->clientTagService->createWorkContactTags($data);

        if ($res != true) {
            throw new CommonException(ErrorCode::SERVER_ERROR, '客户标签创建失败');
        }
        return [];
    }

    /**
     * @return string[] 规则
     */
    public function rules(): array
    {
        return [
            'groupId' => 'required|integer|min:1|bail',
            'tagName' => 'required',
        ];
    }

    /**
     * 获取已定义验证规则的错误消息.
     */
    public function messages(): array
    {
        return [
            'groupId.required' => '分组id必传',
            'tagName.required' => '标签名称必传',
        ];
    }
}
